import apis from './modules';
// import { showLoading, hideLoading } from '../commons/loading';
import { ERROR_MESSAGE_CODE, ERROR_PAGE_CODE, EMPTY_PAGE_PATH } from './const';
import storage from '@/commons/storage';

/** http 请求计数器 */
let httpCounter = 0;

/** 是否存在toast */
let isToast = false;

const BASE_API_URL = import.meta.env.VITE_BASE_API_URL;

/**
 * 开启Loading效果
 * @param {*} sld
 */
export const startShowLoading = sld => {
    if (httpCounter === 0 && sld && !isToast) {
        // showLoading();
    }
};

/**
 * 关闭Loading效果
 */
const endShowLoading = () => {
    if (httpCounter > 0) {
        httpCounter--;
    }
    if (httpCounter === 0 && !isToast) {
        // hideLoading();
    }
};

/**
 * 弹框提示
 * @param {*} title
 */
const toastHandler = title => {
    endShowLoading();
    isToast = true;
    uni.showToast({
        title,
        icon: 'none',
        duration: 2000
    });
    setTimeout(() => {
        isToast = false;
    }, 2000);
};

/**
 * 获取请求信息
 * @param {请求名称} name
 */
export const getApi = name => {
    const api = apis.filter(v => {
        return v.name === name;
    });
    if (api.length === 0) {
        throw new Error(`未找到${name}对应的API服务地址`);
    } else {
        return api[0];
    }
};

/**
 * 封装请求头部信息
 * @param {头部信息} header
 * @param {接口入参} data
 */
export const getHeader = function () {
    const target = {
        'ZW-PLATFORM-TOKEN': storage.get('ZW-PLATFORM-TOKEN') || '',
        'ZW-TENANT-ID': storage.get('ZW-TENANT-ID') || '',
        'ZW-SHOP-ID': storage.get('ZW-SHOP-ID') || ''
    };

    return target;
};

/**
 * 请求成功处理函数
 * @param {*} req
 * @param {*} res
 * @param {*} resolve
 * @param {*} reject
 */
export const successHandler = (req, res, resolve, reject) => {
    if (res.data.code === 0) {
        resolve(res.data);
        endShowLoading();
    } else if (res.data.code === 10401) {
        toastHandler('登录失效');
        endShowLoading();
    } else {
        errorHandler(req, res, reject);
    }
};

export const errorHandler = function (req, res, reject) {
    let title = '';
    if (res.statusCode === 200) {
        /**
         * 如果是501且pem为false 则拦截
         * 如果是501且pem为true 则放开
         * 如果不是501且pem为false 则拦截
         * 如果不是501且pem为true 则放开
         */
        if ([501].includes(res.data.code)) {
            if (!req.pem) {
                title = ERROR_MESSAGE_CODE[res.data.code];
            }
        } else {
            if (!req.pem) {
                title = res.data.msg;
            }
        }
    } else {
        if (res.statusCode === 429) {
            if (req.lmt === 0) {
                title = ERROR_MESSAGE_CODE[res.statusCode];
            } else if (req.lmt === -1) {
                return false;
            } else if (req.lmt === 2) {
                uni.navigateTo({ url: EMPTY_PAGE_PATH });
            }
        } else if (ERROR_PAGE_CODE[res.statusCode]) {
            uni.navigateTo({
                url: ERROR_PAGE_CODE[res.statusCode]
            });
        } else {
            title = ERROR_MESSAGE_CODE['other'];
            // 需要sentry来处理
        }
    }
    if (title) {
        toastHandler(title);
    } else {
        endShowLoading();
        reject(res);
    }
};

/**
 * 请求失败处理函数
 * @param {*} err
 */
export const failHandler = err => {
    const title = ERROR_MESSAGE_CODE['other'];
    toastHandler(title);
};
